// pagesMine/pages/reportDetails/reportDetails.js
import ajax from "../../../utils/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderStatus: ['报备中', '报备成功', '报备失败'], //订单状态：0下订单；1成交； 2订单失败
    /**
     * 详情id
     */
    detailId: null,
    /**
     * 详情对象
     */
    entity: null,
    /**
     * 园区对象
     */
    garden: null,
    /**
     * 图片列表
     */
    lookHousingImage: [],
    /**
     * 上传图片数组
     */
    upLoadImageArr: [],
    /**
     * 禁用状态
     */
    disabled: false,
    /**
     * input选中下标
     */
    focusActive: 0,
    /**
     * 获取焦点状态
     */
    inputFocus: true,
    /**
     * 提交步骤 0验证码 1上传图片 2审核驳回
     */
    submitStep: 0,
    /**
     * 弹出框
     */
    showMode: false,
    /**
     * 表单
     */
    formData: {
      verificationCode: '',
      codeArr: ['', '', '', ''],
    },
    /**
     * 拒绝报备理由
     */
    checkReason: '',
    /**
     * 是否可以查看验证码
     */
    isCode: false,
    /**
     * 是否可以进行审核
     */
    check: false,
    /**
     * 正在上传图片 状态
     */
    chooseImage: false
  },
  /**
   * 查看code / 失败原因
   */
  failureAuditEvent(event) {
    const type = event.currentTarget.dataset.type
    if (type == 1) return wx.showModal({ title: '提示', content: this.data.entity.verificationCode, showCancel: false })
    wx.showModal({ title: '失败原因', content: this.data.entity.checkReason, showCancel: false })
  },
  /**
   * 拒绝报备理由
   */
  rejectTextareaChange(event) {
    this.setData({ checkReason: event.detail.value })
  },
  /**
   * 获取定位
   */
  async getLocation() {
    const res = await ajax.getLocation()
    console.log(res)
  },
  /**
   * 验证码input变化事件
   */
  codeInputChange(event) {
    let { formData, focusActive } = this.data
    let value = event.detail.value
    formData.verificationCode = value
    formData.codeArr = value.split('');
    const count = 4 - formData.codeArr.length
    for (let index = 0; index < count; index++) formData.codeArr.push("");
    focusActive = value.length < 4 ? value.length : 3
    this.setData({ formData, focusActive })
    if (value.length >= 4) {
      this.cancelMode()
      this.submitEvent()
    }
  },
  /**
   * 验证码点击事件
   */
  codeItemEvent(event) {
    const { formData } = this.data
    const count = formData.verificationCode.length
    this.setData({ focusActive: count < 4 ? count : 3, inputFocus: true })
  },
  /**
   * 删除图片
   */
  async deleteImageEvent(event) {
    const { upLoadImageArr } = this.data
    const index = event.currentTarget.dataset.index
    upLoadImageArr.splice(index, 1)
    this.setData({ upLoadImageArr })
  },
  /**
   * 上传图片事件
   */
  async upLoadImageEvent() {
    const { upLoadImageArr } = this.data
    this.data.chooseImage = true
    const filePath = await ajax.chooseImage()
    upLoadImageArr.push(filePath)
    this.setData({ upLoadImageArr })
  },
  /**
   * 确认上传事件
   */
  async confirmUpload() {
    const { upLoadImageArr, entity } = this.data
    this.cancelMode()
    ajax.showLoading()
    const urlList = [];
    for (let index = 0; index < upLoadImageArr.length; index++) {
      const element = upLoadImageArr[index];
      const res = await ajax.uploadFile({ filePath: element })
      urlList.push(res.data.url)
    }
    await ajax.post('/workorder/lookHousingOrderImage/addBatch', { lookHousingId: entity.id, image: urlList })
    await ajax.showSuccess('操作成功')
    this.getDetailRequest()
  },
  /**
   * 确认看房 - 定位授权
   */
  locationAccredit() {
    const { lookHousingStatus, id, beginLatitude } = this.data.entity
    if (lookHousingStatus != 1 && beginLatitude) return
    wx.showModal({
      title: '获取定位授权',
      content: '您的位置信息将用于平台审核',
      success: async (modal) => {
        if (!modal.confirm) return;
        const res = await ajax.getLocation()
        const formData = { id, beginLatitude: res.latitude, beginLongitude: res.longitude }
        ajax.showLoading()
        await ajax.post('/workorder/lookHousingOrder/updateBeginItude', formData).finally(() => wx.hideLoading());
        await ajax.showSuccess('操作成功')
        this.getDetailRequest()
      }
    })
  },
  /**
   * 隐藏操作提示框
   */
  cancelMode() {
    this.data.chooseImage = false
    this.setData({ showMode: false })
  },
  /**
   * 审核事件
   */
  async auditRequestEvent(event) {
    const { entity, checkReason } = this.data
    const type = event.currentTarget.dataset.type
    if (type == 4 && !checkReason) return ajax.showToast('请填写拒绝理由')
    wx.showModal({
      title: '提示',
      content: `确定${type == 4 ? '拒绝' : '通过'}该报备吗?`,
      success: async (res) => {
        if (!res.confirm) return
        const formData = { checkReason, id: entity.id, lookHousingStatus: type }
        this.cancelMode()
        ajax.showLoading()
        await ajax.post('/workorder/lookHousingOrder/updateCheckHousingOrder', formData).finally(() => wx.hideLoading())
        await ajax.showSuccess('操作成功')
        this.getDetailRequest()
      }
    })
  },
  /**
   * 显示操作框
   */
  async showMode(event) {
    const { lookHousingStatus } = this.data.entity
    if (lookHousingStatus == 2 || lookHousingStatus == 5) return
    const submitStep = event.currentTarget.dataset.type
    await this.getDetailRequest()
    if (submitStep == 0 && !this.data.lookHousingImage.length) return ajax.showToast('请上传图片')
    this.setData({ showMode: true, submitStep: submitStep })
  },
  /**
   * 看房完成提交事件
   */
  async submitEvent() {
    const { formData, entity } = this.data
    ajax.showLoading()
    formData.id = entity.id
    await ajax.post('/workorder/lookHousingOrder/confirmHousing', formData).finally(() => wx.hideLoading())
    await ajax.showToast("操作成功,请等待审核")
    this.getDetailRequest()
  },
  /**
   * 打电话
   */
  callUpEvent() {
    ajax.makePhoneCall(this.data.entity.customerMobile)
  },
  /**
   * 打开地图
   */
  openMap() {
    const { province, city, county, address } = this.data.garden
    ajax.openMmap(`${province}${city}${county}${address}`)
  },
  /**
   * 获取工单详情
   */
  async getDetailRequest() {
    const res = await ajax.get(`/workorder/lookHousingOrder/info?id=${this.data.detailId}`)
    const { isCode, check } = res
    const entity = res.data.lookHousingOrder
    const lookHousingImage = res.data.lookHousingImage || []
    // 0等待确认；1等待看房；2看房完成(已完成)；3发放佣金；4报备失败(审核拒绝)；5报备超时
    const disabled = entity.lookHousingStatus == 2 || entity.lookHousingStatus == 5
    const beginTime = ajax.dayjs(entity.beginTime).format('YYYY-MM-DD HH:ss')
    const endTime = ajax.dayjs(entity.endTime).format('HH:ss')
    entity.lookTime = `${beginTime} - ${endTime}`
    const upLoadImageArr = lookHousingImage.map(item => item.image)
    this.setData({ entity, garden: res.data.garden, lookHousingImage, disabled, upLoadImageArr, isCode, check })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ detailId: options.detailId })
    this.getDetailRequest()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.chooseImage ? null : this.getDetailRequest()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})